package io.zerax.moyu_chat;

import android.app.*;
import android.os.*;
import android.widget.*;
import android.content.res.Resources;
import java.util.ArrayList;
import android.view.Menu;
import android.view.View;
import android.view.MenuItem;
import android.view.View.OnKeyListener;
import android.view.KeyEvent;

public class MainActivity extends Activity
{
    private String userName;
    private MessageAdapter adapter;
    private EditText msgInput;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        userName = getIntent().getExtras().getString("chat_name");
        
        msgInput = findViewById(R.id.sender);
		
		msgInput.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(android.view.View p1, int p2, android.view.KeyEvent event) {
				if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
					String input = msgInput.getEditableText().toString();
					MainActivity.this.send(input);
					return true;
				}
				return false;
			}
		});
        
        adapter = new MessageAdapter(this);
        
        ListView list = findViewById(R.id.msg_panel);
        list.setAdapter(adapter);
        this.setTitle(getString(R.string.app_name) + " - " + userName);
    }
    
    public void onSend(View v) 
    {
        String msg = msgInput.getEditableText().toString();
        send(msg);
    }
	
	private void send(String msg) {
		adapter.insert(new Message(userName, true, msg), 0);
		msgInput.getEditableText().clear();
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        if (item.getItemId() == R.id.connect) {
            ConnectDialogFragment cdf = new ConnectDialogFragment();
			cdf.addOnValueInputListener(new ConnectDialogFragment.OnValueInput() {
				@Override
				public void input(String msg, boolean isRoom)
				{
					String type = "";
					if (isRoom) {
						type = "Room";
					} else {
						type = "P2P";
					}
					Toast.makeText(MainActivity.this, "Connect[" + type + "]:" + msg, Toast.LENGTH_SHORT).show();
				}
			});
			cdf.show(getFragmentManager(), "connect");
        }
        return false;
    }
}
